import type { MqttClient, OnMessageCallback } from 'mqtt';
import * as mqtt from 'mqtt/dist/mqtt.min.js';
import { uuid } from 'vue-uuid';
import { IMQConfig } from './Model';

class MQTT {
  url: string;
  config: IMQConfig;
  client!: MqttClient;
  constructor(config: IMQConfig) {
    this.config = config;
    this.url = 'ws://' + this.config.mqtt + '/ws';// ws方式必须ws结尾
  }

  //初始化mqtt
  init() {
    const options = {
      clean: true,
      clientId: this.config.id + "_" + uuid.v1(),
      username: this.config.username,
      password: this.config.password,
      connectTimeout: this.config.connectTimeout, // 超时时间
      //重连间隔时间，单位为毫秒，默认为 1000 毫秒，注意：当设置为 0 以后将取消自动重连
      // reconnectPeriod:0
    };

    this.client = mqtt.connect(this.url, options);

    this.client.on('error', () => {
      console.log(this.url + "异常中断");
    });

    this.client.on('reconnect', () => {
      console.log(this.url + "重新连接");
    });
  }

  //取消订阅
  unsubscribes(topic: string) {
    this.client.unsubscribe(topic, (error: Error) => {
      if (!error) {
        console.log(topic + '取消订阅成功');
      } else {
        console.log(topic + '取消订阅失败');
      }
    });
  }

  //连接
  link(topic: string) {
    //这里客户端已经初始化好了，不监听连接事件，直接监听
    // this.client.on('connect', () => {
      this.client.subscribe(topic, (error: any) => {
        if (!error) {
          console.log(topic + '订阅成功');
        } else {
          console.log(topic + '订阅失败');
        }
      // });
    });
  }

  //收到的消息
  get(callback: OnMessageCallback) {
    this.client.on('message', callback);
  }

  //结束链接
  over() {
    this.client.end();
  }
  //发送消息
  publish(topic,message,callback){
    this.client.publish(topic,message, { qos: 1 },callback);
  }
  getClient(){
    return this.client;
  }
}
export default MQTT;

